import pandas as pd
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
import mplfinance as mpf

class KlineCanvas(FigureCanvas):
    def __init__(self, parent=None):
        # 设置全局字体大小
        plt.rcParams.update({
            'xtick.labelsize': 12,
            'ytick.labelsize': 12,
            'axes.titlesize': 14
        })
        plt.rcParams["font.family"] = ["SimHei"]
        self.fig, self.ax = plt.subplots(figsize=(10, 6), dpi=100)
        super().__init__(self.fig)
        self.setParent(parent)
    def axisSet(self,dataframe):# 调整坐标轴范围
        if not dataframe.empty:
            min_price = dataframe['low'].min()
            max_price = dataframe['high'].max()
            margin = (max_price - min_price) * 0.1  # 10%边距
            self.ax.set_xlim(-1, int(len(dataframe)*1.1))
            self.ax.set_ylim(min_price - margin, max_price + margin)
    def handleData(self,kline):
        kline = kline.copy()
        kline['datetime'] = pd.to_datetime(kline['datetime'])  # 确保类型正确
        kline = kline.set_index('datetime')  # 设置为索引
        
        return kline
    def drawData(self,dataframe,title):
        self.ax.clear()
        self.axisSet(dataframe)
        if dataframe.empty:return
        dataframe=self.handleData(dataframe)
        mc = mpf.make_marketcolors(# 自定义K线颜色：上涨（收盘价>开盘价）为红色，下跌为绿色
            up='red',        # 上涨K线颜色
            down='green',    # 下跌K线颜色
            edge='i',        # 边缘颜色（i表示继承主体颜色）
            wick='i',        # 上下影线颜色（i表示继承主体颜色）
            volume='in',     # 成交量颜色（in表示与K线同色）
            ohlc='i',         # OHLC线颜色（i表示继承主体颜色）
        )
        # 创建自定义样式
        s = mpf.make_mpf_style(
            marketcolors=mc,
            )
        mpf.plot(
                dataframe,
                type='candle',
                ax=self.ax,
                ylabel='',
                style=s,
                volume=False
                )
        # 刷新画布
        
        self.ax.yaxis.grid(
            True,
            linestyle='--',
            color='gray',
            alpha=0.3  # 这里可以直接使用alpha参数（matplotlib原生支持）
        )
        self.ax.xaxis.grid(False)  # 隐藏纵向网格线
        self.ax.set_title(title)
        self.fig.canvas.draw()
